﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

namespace SeatSet
{
    public partial class Main : Form
    {        
        //设定程序临时文件路径
        string temppath = Application.StartupPath+"\\temp";
        //设定程序路径
        string apppath = Application.StartupPath;
        //user32.dll是非托管代码，不能用命名空间的方式直接引用，
        //所以需要用“DllImport”进行引入后才能使用   
        [DllImport("user32.dll", SetLastError = true)]   
        public static extern bool RegisterHotKey(   
            IntPtr hWnd, //要定义热键的窗口的句柄  
            int id, //定义热键ID（不能与其它ID重复）  
            //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
            KeyModifiers fsModifiers,
            Keys vk //定义热键的内容
            );
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd, 
            //要取消热键的窗口的句柄
            int id //要取消热键的ID
            );    //定义了辅助键的名称（将数字转变为字符以便于记忆，也可去除此枚举而直接使用数值）
        [Flags()]
        public enum KeyModifiers
        {   
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8,
            CtrlAndShift = 6 
        }
        public bool IsExist;
        public List<student> stu=new List<student>();//内存建立学生列表
        string OpenedPath="";//打开的文件的路径
        public Main(string[] args)
        {
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
            try
            {
                OpenChart(args[0]);//打开拖动到程序的文件
                this.Text = "座次表排序软件——" + args[0].Split(new char[] { '\\' })[args[0].Split(new char[] { '\\' }).Length - 1];
                GobleVar.NeedSave = false;
            }
            catch (Exception)
            {
            }
        }
        public Main()
        {
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog3.ShowDialog();
        }

        private void Btn_Add_Click(object sender, EventArgs e)
        {
            if (TB_StuName.Text == "")
            {
                MessageBox.Show("姓名不能为空！");
            }
            else if (!RB_Boy.Checked && !RB_Girl.Checked)
            {
                MessageBox.Show("请选择性别！");
            }
            else
            {
                stu.ForEach(MathChar);
                if (IsExist)
                {
                    MessageBox.Show("学生已存在！");
                    IsExist = false;
                }
                else if (RB_Boy.Checked)
                {
                    stu.Add(new student(TB_StuName.Text, true));
                    listView1.Items.Add(TB_StuName.Text, 0);
                    GobleVar.NeedSave = true;
                }
                else
                {
                    stu.Add(new student(TB_StuName.Text, false));
                    listView1.Items.Add(TB_StuName.Text, 1);
                    GobleVar.NeedSave = true;
                }
            }
        }
        public class student
        {
            private string name;
            private bool sex;
            public student(string Name, bool Sex)
            {
                this.name = Name;
                this.sex = Sex;
            }
            public student(string Name)
            {
                this.name = Name;
            }
            public string Name
            {
                get { return name; }
                set { this.name = value; }
            }
            public bool Sex
            {
                get { return sex; }
                set { this.sex = value; }
            }
        }
        private void Btn_Delete_Click(object sender, EventArgs e)
        {
            List<student> remove = new List<student>();
            remove = stu.FindAll(RemoveSelect);
            foreach (student temp in remove)
            {
                stu.Remove(temp);
            }
            listView1.Items.Remove(listView1.FocusedItem);
            GobleVar.NeedSave = true;
        }
        private bool RemoveSelect(student Student)
        {
            if (Student.Name == listView1.FocusedItem.Text)
                return true;
            else
                return false;
        }
        private void MathChar(student student)
        {
            if (student.Name == TB_StuName.Text)
                IsExist=true;
        }

        private void Btn_OutPut_Click(object sender, EventArgs e)
        {
            saveFileDialog1.ShowDialog();
        }
        DataSet save = new DataSet(),open=new DataSet();
        OleDbConnection cn;
        OleDbCommand cmd;
        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            
            if (saveFileDialog1.FileName.EndsWith(".xls"))
            {
                String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + saveFileDialog1.FileName + ";" + "Extended Properties=Excel 8.0;";
                OleDbConnection cn = new OleDbConnection(sConnectionString);
                string sqlCreate = "CREATE TABLE 学生列表 ([学生姓名] VarChar,[学生性别] VarChar)";
                OleDbCommand cmd = cn.CreateCommand();
                cmd.CommandText = sqlCreate;
                //创建Excel文件
                cn.Open();
                //创建工作表
                cmd.ExecuteNonQuery();
                stu.ForEach(writeToXls);
                //关闭连接
                cn.Close();
            }
            else if (saveFileDialog1.FileName.EndsWith(".xml"))
            {
                save = new DataSet();
                save.Clear();
                save.DataSetName = "学生列表";
                save.Tables.Add("学生列表");
                save.Tables[0].Columns.Add("学生姓名");
                save.Tables[0].Columns.Add("学生性别");
                stu.ForEach(saveToSet);
                save.WriteXml(saveFileDialog1.FileName);
            }
        }
        private void saveToSet(student Student)
        {
            save.Tables[0].Rows.Add(save.Tables[0].NewRow());
            save.Tables[0].Rows[save.Tables[0].Rows.Count-1].ItemArray = new object[] { Student.Name, Student.Sex ? "男" : "女" };
        }
        private void writeToXls(student Student)
        {
            String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + saveFileDialog1.FileName + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection cn = new OleDbConnection(sConnectionString);
            OleDbCommand cmd = cn.CreateCommand();
            cn.Open();
            cmd.CommandText = "INSERT INTO 学生列表 VALUES('"+Student.Name+"','";
            if(Student.Sex)
            {
                cmd.CommandText+="男')";
            }
            else
            {
                cmd.CommandText+="女')";
            }
            cmd.ExecuteNonQuery();

        }
        private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            student dent=new student(listView1.FocusedItem.Text,listView1.FocusedItem.ImageIndex==0?true:false);
            listView1.DoDragDrop(listView1.FocusedItem.Text + ","+Convert.ToString(listView1.FocusedItem.ImageIndex), DragDropEffects.Move);
            listView1.Items.Remove(listView1.FocusedItem);
        }

        private void paintPanel1_DragDrop(object sender, DragEventArgs e)
        {
            string dropdata = e.Data.GetData(typeof(string)).ToString();
            student dent = new student(dropdata.Split(new char[] { ',' })[0], dropdata.Split(new char[] { ',' })[1] == "0" ? true : false);
            if (dent.Sex)
            {
                Point lefttoppoint = this.PointToScreen(this.paintPanel1.Location);
                PaintUnit item = new PaintUnit(dent.Name, imageList1.Images[0],
                    ItemStatus.Actived,
                    new Point(e.X - lefttoppoint.X - imageList1.Images[0].Width / 2,
                        e.Y - lefttoppoint.Y - imageList1.Images[0].Height / 2), new Pen(Color.Gray), this.Font);
                this.paintPanel1.PaintItems.Add(item);
                this.paintPanel1.Refresh();
            }
            else
            {
                Point lefttoppoint = this.PointToScreen(this.paintPanel1.Location);
                PaintUnit item = new PaintUnit(dent.Name, imageList1.Images[1],
                    ItemStatus.Actived,
                    new Point(e.X - lefttoppoint.X - imageList1.Images[1].Width / 2,
                        e.Y - lefttoppoint.Y - imageList1.Images[1].Height / 2), new Pen(Color.Gray), this.Font);
                this.paintPanel1.PaintItems.Add(item);
                this.paintPanel1.Refresh();
            }
            GobleVar.NeedSave = true;
            this.Text += "*";
        }

        private void paintPanel1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }
        private void Btn_Input_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }
        DataRow compare;
        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            if (openFileDialog1.FileName.EndsWith(".xml"))
            {
                open = new DataSet();
                open.Clear();
                open.DataSetName = "学生列表";
                open.Tables.Add("学生列表");
                open.Tables[0].Columns.Add("学生姓名");
                open.Tables[0].Columns.Add("学生性别");
                open.ReadXml(openFileDialog1.FileName,XmlReadMode.IgnoreSchema);
                foreach (DataRow row in open.Tables[0].Rows)
                {
                    compare = row;
                    stu.ForEach(MathStudent);
                    if (!IsExist)
                    {
                        stu.Add(new student(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男"));
                        listView1.Items.Add(new ListViewItem(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男" ? 0 : 1));
                    }
                }
            }
            else if (openFileDialog1.FileName.EndsWith(".xls"))
            {
                OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + openFileDialog1.FileName + ";" + "Extended Properties=Excel 8.0;");
                OleDbCommand com = con.CreateCommand();
                DataSet set = new DataSet();
                try
                {
                    com.CommandText = "SELECT * FROM [学生列表$]";
                    OleDbDataAdapter adpter = new OleDbDataAdapter(com);                    
                    adpter.Fill(set);
                }
                catch (Exception)
                {
                    MessageBox.Show("学生信息表格式不正确!");
                    return;
                }
                foreach (DataRow row in set.Tables[0].Rows)
                {
                    compare = row;
                    stu.ForEach(MathStudent);
                    if (!IsExist)
                    {
                        stu.Add(new student(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男"));
                        listView1.Items.Add(new ListViewItem(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男" ? 0 : 1));
                    }
                }
            }
            GobleVar.NeedSave = true;
        }
        private void MathStudent(student student)
        {
            if (student.Name == Convert.ToString(compare["学生姓名"]))
                IsExist = true;
            else
                IsExist = false;
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog2.ShowDialog();
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog2.ShowDialog();
        }

        private void saveFileDialog2_FileOk(object sender, CancelEventArgs e)
        {
            SaveChart(saveFileDialog2.FileName);
            this.Text = "座次表排序软件——" + saveFileDialog2.FileName.Split(new char[] { '\\' })[saveFileDialog2.FileName.Split(new char[] { '\\' }).Length - 1];
            GobleVar.NeedSave = false;
        }

        private void SaveChart(string filename)
        {
            SerializeObjectToFile(temppath + "\\temp.scf");
            save = new DataSet();
            save.Clear();
            save.DataSetName = "学生列表";
            save.Tables.Add("学生列表");
            save.Tables[0].Columns.Add("学生姓名");
            save.Tables[0].Columns.Add("学生性别");
            stu.ForEach(saveToSet);
            StreamWriter config = new StreamWriter(temppath + "\\temp.ini");
            config.WriteLine("Width=" + Convert.ToString(this.Size.Width));
            config.WriteLine("Height=" + Convert.ToString(this.Size.Height));
            config.Write("Spliter=" + Convert.ToString(splitContainer1.SplitterDistance));
            config.Close();
            save.WriteXml(temppath + "\\temp.xml");
            string[] file = new string[2];
            file[0] = temppath;
            file[1] = filename.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)[filename.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Length - 1];
            Compression.ZipClass zip = new Compression.ZipClass();
            zip.ZipFileMain(file);
            File.Delete(temppath + "\\temp.scf");
            File.Delete(temppath + "\\temp.xml");
            File.Delete(temppath + "\\temp.ini");
            GobleVar.NeedSave = false;
        }
        internal void SerializeObjectToFile(string storefilename)
        {
            IFormatter formatter = new BinaryFormatter();
            Stream writer = new FileStream(storefilename, FileMode.Create); 
            formatter.Serialize(writer, paintPanel1.PaintItems);
            byte[] objbuffer = new byte[writer.Length];
            writer.Seek(0, SeekOrigin.Begin);
            writer.Read(objbuffer, 0, objbuffer.Length);
            writer.Close();
        }   
        private void openFileDialog2_FileOk(object sender, CancelEventArgs e)
        {
            OpenChart(openFileDialog2.FileName);
            this.Text = "座次表排序软件——" + openFileDialog2.FileName.Split(new char[] { '\\' })[openFileDialog2.FileName.Split(new char[] { '\\' }).Length - 1];
            GobleVar.NeedSave = false;
        }

        private void OpenChart(string filename)
        {
            string[] file = new string[2];
            file[0] = filename;
            file[1] = temppath + "\\";
            DeCompression.UnZipClass unzip = new DeCompression.UnZipClass();
            unzip.UnZip(file);
            open = new DataSet();
            open.Clear();
            open.DataSetName = "学生列表";
            open.Tables.Add("学生列表");
            open.Tables[0].Columns.Add("学生姓名");
            open.Tables[0].Columns.Add("学生性别");
            open.ReadXml(temppath + "\\temp.xml", XmlReadMode.IgnoreSchema);
            foreach (DataRow row in open.Tables[0].Rows)
            {
                compare = row;
                stu.ForEach(MathStudent);
                if (!IsExist)
                {
                    stu.Add(new student(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男"));
                    listView1.Items.Add(new ListViewItem(Convert.ToString(row["学生姓名"]), Convert.ToString(row["学生性别"]) == "男" ? 0 : 1));
                }
            }
            StreamReader sr = new StreamReader(temppath + "\\temp.ini");
            this.Size = new System.Drawing.Size(Convert.ToInt32(sr.ReadLine().Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]), Convert.ToInt32(sr.ReadLine().Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]));
            splitContainer1.SplitterDistance = Convert.ToInt32(sr.ReadLine().Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]);
            sr.Close();
            paintPanel1.PaintItems.Clear();
            paintPanel1.Refresh();
            this.paintPanel1.PaintItems = UnSerializeObjectFromFile(temppath + "\\temp.scf");
            foreach (ListViewItem item in listView1.Items)
            {
                foreach (IPaintItem paint in paintPanel1.PaintItems)
                {
                    if (item.Text == paint.ItemName)
                    {
                        listView1.Items.Remove(item);
                    }
                }
            }
            OpenedPath = filename;
            this.paintPanel1.Refresh();
        }
        internal List<IPaintItem> UnSerializeObjectFromFile(string storefilename)
        {
            List<IPaintItem> offlineobject = null;
            IFormatter formatter = new BinaryFormatter();
            Stream writer = new FileStream(storefilename, FileMode.Open);// new IsolatedStorageFileStream(string.Concat(@"OBU\", storefilename), FileMode.OpenOrCreate, isoStore);
            writer.Seek(0, SeekOrigin.Begin);
            offlineobject = (List<IPaintItem>)formatter.Deserialize(writer);
            writer.Close();
            return offlineobject;
        }
        static IPaintItem selectedunit;
        private void paintPanel1_MouseUp(object sender, MouseEventArgs e)
        {
            selectedunit = this.paintPanel1.GetItemAtPoint(e.Location);
            if (selectedunit != null)
            {
                if (selectedunit.ItemLocate.X < 0 || selectedunit.ItemLocate.Y < 0 || selectedunit.ItemLocate.X > paintPanel1.Size.Width || selectedunit.ItemLocate.Y > paintPanel1.Size.Height)
                {
                    paintPanel1.PaintItems.Remove(selectedunit);
                    System.IO.MemoryStream ImageMem = new System.IO.MemoryStream();
                    listView1.Items.Add(selectedunit.ItemName, stu[stu.FindIndex(StudentSelect)].Sex ? 0 : 1);
                    GobleVar.NeedSave = true;
                }
            }
        }
        private static bool StudentSelect(student Student)
        {
            if (Student.Name == selectedunit.ItemName)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void saveFileDialog3_FileOk(object sender, CancelEventArgs e)
        {
            paintPanel1.ShowGrid = false;
            String Mode;
            if (MessageBox.Show("您是否要输出为姓名模式？", "选择输出模式", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                NameMode();
                Mode = "Name";
            }
            else
            {
                NameMode();
                IconMode();
                Mode = "Icon";
            }
            Bitmap output = new Bitmap(paintPanel1.Size.Width, paintPanel1.Size.Height);
            paintPanel1.DrawToBitmap(output, new Rectangle(paintPanel1.Location, paintPanel1.Size));
            if (saveFileDialog3.FileName.EndsWith(".jpeg"))
            {
                output.Save(saveFileDialog3.FileName, ImageFormat.Jpeg);
            }
            else if (saveFileDialog3.FileName.EndsWith(".bmp"))
            {
                output.Save(saveFileDialog3.FileName, ImageFormat.Bmp);
            }
            else if (saveFileDialog3.FileName.EndsWith(".gif"))
            {
                output.Save(saveFileDialog3.FileName, ImageFormat.Gif);
            }else if (saveFileDialog3.FileName.EndsWith(".png"))
            {
                output.Save(saveFileDialog3.FileName, ImageFormat.Png);
            }
            else if (saveFileDialog3.FileName.EndsWith(".tif"))
            {
                output.Save(saveFileDialog3.FileName, ImageFormat.Tiff);
            }
            paintPanel1.ShowGrid = true;
            if (Mode == "Name")
            {
                IconMode();
            }
        }
        List<student> stuin = new List<student>();
        private void NameMode()
        {
            stuin.Clear();
            foreach (IPaintItem item in paintPanel1.PaintItems)
            {
                selectedunit = item;
                stuin.Add(new student(item.ItemName, stu[stu.FindIndex(StudentSelect)].Sex));
                Image img = new Bitmap(55, 55);
                Graphics g = Graphics.FromImage(img);
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                g.DrawString(item.ItemName,new Font("微软雅黑",10,FontStyle.Regular), new SolidBrush(Color.Black), 10, 10);
                item.ItemImage = img;
                item.ItemName = "";
                paintPanel1.Refresh();
            }
        }

        private void IconMode()
        {
            int i = 0;
            foreach (IPaintItem item in paintPanel1.PaintItems)
            {
                selectedunit = item;
                item.ItemName = stuin[i].Name;
                item.ItemImage = stuin[i].Sex ? imageList1.Images[0] : imageList1.Images[1];
                i++;
                paintPanel1.Refresh();
            }
            stuin.Clear();
        }

        private void 在线升级ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var updater = FSLib.App.SimpleUpdater.Updater.Instance;
            FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple();
            updater.Error += new EventHandler(updater_Error);
            updater.NoUpdatesFound += new EventHandler(updater_NoUpdatesFound);
        }

        void updater_NoUpdatesFound(object sender, EventArgs e)
        {
            MessageBox.Show("当前程序已经是最新！");
        }

        void updater_Error(object sender, EventArgs e)
        {
            MessageBox.Show("更新出现错误！");
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.Show();
        }

        private void splitContainer1_Panel1_Resize(object sender, EventArgs e)
        {
            paintPanel1.Size = splitContainer1.Panel1.ClientSize;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(Application.StartupPath + "\\temp"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\temp");
            }
            RegisterHotKey(Handle, 100, KeyModifiers.Ctrl, Keys.S);
            //注册Ctrl+S快捷键
        }
        protected override void WndProc(ref Message m) 
        {  
            const int WM_HOTKEY = 0x0312;
            //按快捷键
            switch (m.Msg)
            { 
                case WM_HOTKEY:
                switch (m.WParam.ToInt32())
                { 
                    case 100: //按下的是Ctrl+S
                        if (OpenedPath != "")
                        {
                            SaveChart(OpenedPath);
                            this.Text = "座次表排序软件——" + OpenedPath.Split(new char[] { '\\' })[OpenedPath.Split(new char[] { '\\' }).Length - 1];
                            GobleVar.NeedSave = false;
                        }
                        else
                        {
                            saveFileDialog2.ShowDialog();
                        }
                        break;                         
                }  
                break; 
            } 
            base.WndProc(ref m);
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            //注销Id号为100的热键设定
            UnregisterHotKey(Handle, 100);
            File.Delete(temppath + "\\temp.scf");
            File.Delete(temppath + "\\temp.xml");
            File.Delete(temppath + "\\temp.ini");
            backgroundWorker1.CancelAsync();
            Application.Exit();
        }

        private void Main_Deactivate(object sender, EventArgs e)
        {
            UnregisterHotKey(Handle, 100);
        }

        private void Main_Activated(object sender, EventArgs e)
        {
            RegisterHotKey(Handle, 100, KeyModifiers.Ctrl, Keys.S);
        }
        private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
        {
            paintPanel1.PaintItems.Clear();
            listView1.Items.Clear();
            stu.Clear();
            stuin.Clear();
            File.Delete(temppath + "\\temp.scf");
            File.Delete(temppath + "\\temp.xml");
            File.Delete(temppath + "\\temp.ini");
            this.Text += "———未命名*";
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                    if (GobleVar.NeedSave)
                    {
                        if (!this.Text.Contains("*"))
                        {
                            this.Invoke(new Change(Needsave));
                        }
                    }
                    else
                    {
                        if (this.Text.Contains("*"))
                        {
                            this.Invoke(new Change(Needntsave));
                        }
                    }
                }
                catch (Exception)
                { }
            }
        }
        delegate void Change();
        void Needsave()
        {
            this.Text += "*";
        }
        void Needntsave()
        {
            try
            {
                this.Text.Remove(this.Text.Length - 2);
            }
            catch (Exception)
            { }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (GobleVar.NeedSave)
            {
                DialogResult result=MessageBox.Show("您还有文件没有保存，您要先保存吗？", "退出确认", MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    if (OpenedPath != "")
                    {
                        SaveChart(OpenedPath);
                    }
                    else
                    {
                        saveFileDialog2.ShowDialog();
                    }
                    backgroundWorker1.CancelAsync();
                    Application.Exit();
                }
                else if (result == DialogResult.No)
                {
                    backgroundWorker1.CancelAsync();
                    Application.Exit();
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                backgroundWorker1.CancelAsync();
                Application.Exit();
            }
        }
    }
}
namespace Compression
{
    public class ZipClass
    {

        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
        {
            //如果文件没有找到，则报错
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
            }

            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipEntry ZipEntry = new ZipEntry("ZippedFile");
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[BlockSize];
            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
            ZipStream.Write(buffer, 0, size);
            try
            {
                while (size < StreamToZip.Length)
                {
                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                    ZipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            ZipStream.Finish();
            ZipStream.Close();
            StreamToZip.Close();
        }

        public void ZipFileMain(string[] args)
        {
            string[] filenames = Directory.GetFiles(args[0]);

            Crc32 crc = new Crc32();
            ZipOutputStream s = new ZipOutputStream(File.Create(args[1]));

            s.SetLevel(6); // 0 - store only to 9 - means best compression

            foreach (string file in filenames)
            {                
                FileStream fs = File.OpenRead(file);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                ZipEntry entry = new ZipEntry(file.Split(new char[] { '\\' })[file.Split(new char[] { '\\' }).Length - 1]);
                entry.DateTime = DateTime.Now;
                entry.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                s.PutNextEntry(entry);
                s.Write(buffer, 0, buffer.Length);
            }
            s.Finish();
            s.Close();
        }
    }
}
namespace DeCompression
{
    public class UnZipClass
    {
        public void UnZip(string[] args)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {

                string directoryName = Path.GetDirectoryName(args[1]);
                string fileName = Path.GetFileName(theEntry.Name);

                //生成解压目录
                Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    //解压文件到指定的目录
                    FileStream streamWriter = File.Create(args[1] + theEntry.Name);

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }

                    streamWriter.Close();
                }
            }
            s.Close();
        }
    }
}




